package com.example.zhengchaojun.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

import com.zerogis.zcommon.third.xutils.HttpUtils;
import com.zerogis.zcommon.third.xutils.exception.HttpException;
import com.zerogis.zcommon.third.xutils.http.RequestParams;
import com.zerogis.zcommon.third.xutils.http.ResponseInfo;
import com.zerogis.zcommon.third.xutils.http.callback.RequestCallBack;
import com.zerogis.zcommon.third.xutils.http.client.HttpRequest;

public class MainActivity extends AppCompatActivity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void onClick(View view)
    {
        switch (view.getId())
        {
            case R.id.btn_send:
                doClickBtnSend(view);
                break;
            case R.id.btn_method:
                doClickBtnMethod(view);
                break;
        }
    }

    private void doClickBtnSend(View view)
    {
        boolean isActivated = findViewById(R.id.btn_method).isActivated();
        String url = ((TextView) findViewById(R.id.tv_url)).getText().toString();
        String text = ((TextView) findViewById(R.id.et_param)).getText().toString();

        RequestParams params = new RequestParams();
        String[] et_param = text.split(";");
        for (int i = 0; i < et_param.length; i++)
        {// id,0;name,123
            String[] keyValue = et_param[i].split(",");
            params.addBodyParameter(keyValue[0], keyValue[1]);
        }
        netTest(isActivated, url, params);

        ((TextView) findViewById(R.id.tv_text)).setText(url + text);
    }

    private void doClickBtnMethod(View view)
    {
        boolean isActivated = view.isActivated();
        view.setActivated(!isActivated);
        if (isActivated)
        {// false 是post方式
            ((TextView) view).setText("POST方式");
        }
        else
        {
            ((TextView) view).setText("GET方式");
        }
    }

    private void netTest(boolean method, String url, RequestParams params)
    {
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(method ? HttpRequest.HttpMethod.GET : HttpRequest.HttpMethod.POST, url, method ? null : params
                , new RequestCallBack<String>()
                {
                    public void onSuccess(ResponseInfo<String> responseInfo)
                    {
                        String result = responseInfo.result;
                        ((TextView) findViewById(R.id.tv_result)).setText(result);
                    }

                    public void onFailure(HttpException e, String s)
                    {
                        ((TextView) findViewById(R.id.tv_result)).setText(s);
                    }
                });
    }
}
